package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Userinfo;
import cn.wolfcode.crm.mapper.UserinfoMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.query.UserQueryObject;
import cn.wolfcode.crm.service.IUserinfoService;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class UserinfoServiceImpl implements IUserinfoService {

    @Autowired
    private UserinfoMapper userinfoMapper;
    
    public int saveOrUpdate(Userinfo record) {
        if (record.getId() == null) {
            //设置状态为true
            record.setState(true);
            //设置申请时间为当前时间
            record.setApplyTime(new Date());
            //保存信息
            return userinfoMapper.insert(record);
        } else {
            return userinfoMapper.updateByPrimaryKey(record);
        }
    }
    
    public Userinfo selectByPrimaryKey(Long id) {
        return userinfoMapper.selectByPrimaryKey(id);
    }

    
    public List<Userinfo> selectAll() {
        return userinfoMapper.selectAll();
    }

    /**
     * 审核操作
     * @param id
     */
    public void audit(Long id) {
        //根据id查询到当前学生的信息
        Userinfo user = userinfoMapper.selectByPrimaryKey(id);
        //判断其状态是不是正常的
        if(!user.getState()){
            //状态不正常 抛出一个异常
            throw new RuntimeException("该学生的状态属于非正常情况,审核失败!");
        }
        //状态正常 设置当前审核时间 审核状态 审核人
        user.setAuditTime(new Date());
        user.setAuditor(UserContext.getUserContext());
        user.setAuditState(true);
        //更新到这个学生的信息中
        userinfoMapper.audit(user);
    }

    @Override
    public void deleteByStudentId(Long id) {
        userinfoMapper.deleteByStudentId (id);
    }

    /**
     * 根据当前用户名查询当前学生
     * @param studentName
     * @return
     */
    public List<Userinfo> queryByStudentName(String studentName) {
        return userinfoMapper.queryByStudentName(studentName);
    }

    public PageResult query(QueryObject qo) {
        int count = userinfoMapper.queryForCount(qo);
        if (count == 0) {
            return new PageResult(0, Collections.EMPTY_LIST);
        }
        List<Userinfo> data = userinfoMapper.queryForList(qo);
         return new PageResult(count, data);
    }

}
